package com.xwli.springcloud.controller;


import com.alibaba.fastjson.JSON;
import com.xwli.springcloud.projo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    //我们作为消费者去调用远程的服务
    @Autowired
    private RestTemplate restTemplate; //提供多种便捷访问远程restful风格http服务的方法

    //private static final String REST_URL_PREFIX = "http://localhost:8001";

    //Ribbon这个地址应该是服务名
    //Ribbon和Eureka整合以后，客户端就不用关心服务的ip的地址，直接通过服务名去调用
    private static final String REST_URL_PREFIX = "http://springcloud-server-provider";

    @RequestMapping("/dept/list")
    public List<Dept> getDeptList(){
        return restTemplate.getForObject(REST_URL_PREFIX+"/dept/list",List.class);
    }


    /**
     * 添加一个部门信息
     * @param dept
     * @return
     */
    @RequestMapping("/dept/add")
    public boolean addDept(Dept dept){
        String json = JSON.toJSONString(dept);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> stringHttpEntity = new HttpEntity<>(json, httpHeaders);
        Dept dept1 = dept;
        return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add",stringHttpEntity, Boolean.class);
    }

    /**
     * 根据部门编号获取信息
     * @param id
     * @return
     */
    @RequestMapping("/dept/get/{id}")
    public Dept getDeptById(@PathVariable(name = "id")Long id){
        return restTemplate.getForObject(REST_URL_PREFIX+"/dept/get/"+id,Dept.class);
    }
}
